<template>
	<w-table
		ref="listTable"
		:tableColumn="tableColumn"
		:tableValiDate="tableValiDate"
		:tableEditColumnProp="tableEditColumnProp"
		:listData="tableDataComputed"
		:listTotal="tableDataComputed.length || 0"
		:showPagination="false"
    :showColumnFilterBtn="false"
		:showIndex='showIndex'
		:loading="loading"
		:expandRowSlot="expandRowSlot"
		:selectable="selectable"
		:border="border"
		:showTools="showTools"
		minWidth="100px"
		class="fx-details-table"
		@on-row-edit-enter="doRowEditEnter"
		@on-row-edit-up-down-change="setRowEdit"
	>
		<div slot="btn-tools-left" class="tools-left">
			<div class="tools-left-left">
				<w-input
					:value="tableSearchKey"
					placeholder="请输入内容"
					prefix-icon="el-icon-search"
					class="table-search-input"
					@change="onSearchKeyChange"
				>
				</w-input>
			</div>
			<div class="tools-left-right">
				<w-link v-if="expandRowSlot" type="primary" icon="table-details-fold" @click="onAllFoldclick">全部收起</w-link>
				<w-link v-if="expandRowSlot" type="primary" icon="table-details-expand" @click="onAllExpandClick">全部展开</w-link>
				<w-link v-show='showMistakeCheck' type="primary" icon="table-details-safe" @click="onMistakeCheck">防错校验</w-link>
				<w-link v-show='!disabled && canDelete' :disabled="disabled" type="danger" icon="table-details-delete" @click="onDeleteClick">删除</w-link>
				<el-popover v-model="settingPopperVisible" trigger="click" placement="bottom" width="300" v-if="showBatchSet">
					<w-link
						slot="reference"
						:disabled="disabled"
						type="primary"
						icon="table-details-setting"
						@click="onMulitySettingClick"
					>批量设置</w-link>
					<slot name="setting-mulity" :visible="settingPopperVisible"></slot>
				</el-popover>
			</div>
		</div>
		<div v-if="canAdd" slot="btn-tools-right" class="tools-right">
      <el-button type="primary" v-show='!disabled' class="popper-btn" @click="onAddOnce">新增</el-button>
		</div>
		<div v-if="expandRowSlot" slot="row-expand" slot-scope="{ row, $index }">
			<slot name="row-expand" :row="row" :$index="$index"></slot>
		</div>
		<div v-if="tableData.length===0 && canAdd" slot="empty" class="details-table-empty">
			<w-icon type="details-list-empty" class="details-list-empty-icon"></w-icon>
			<div class="details-list-empty-text">暂无数据</div>
		</div>
	</w-table>
</template>
<script>
export default {
	name: 'fx-details-table',
	props: {
		// 列模型
		tableColumn: {
			type: Array,
			default: () => {
				return []
			}
		},
		// table数据
		tableData: {
			type: Array,
			default: () => {
				return []
			}
		},
		// 行校验参数
		tableValiDate: {
			type: Array,
			default: () => {
				return []
			}
		},
		// 可编辑列名
		tableEditColumnProp: {
			type: Array,
			default: () => {
				return []
			}
		},
		// 显示新增/批量新增按钮, 允许自动新增功能
		canAdd: {
			type: Boolean,
			default: true
		},
		canDelete: {
			type: Boolean,
			default: true
		},
		// 开启选择功能
		selectable: {
			type: Boolean,
			default: true
		},
		// 主id
		mainId: String,
		border: Boolean,
		showTools: {
			type: Boolean,
			default: true
		},
		// 开启编辑状态之前
		fpBeforeRowEdit: {
			type: Function,
			default: () => {
				return Promise.resolve()
			}
		},
		// 开启编辑状态
		fpOnRowEdit: Function,
		// 新增明细创建rowData方法
		fpInitAddDetailsData: {
			type: Function,
			default: () => {
				return Promise.resolve({})
			}
		},
		// 保存整单方法
		fpSaveMain: {
			type: Function,
			default: () => {
				return Promise.resolve({})
			}
		},
		// 保存明细方法
		fpSaveDetails: Function,
		// 删除明细方法
		fpDeleteDetails: Function,
		showIndex: {
			type: Boolean,
			default: true
		},
		searchProps: {
			type: Array,
			default: () => {
				return ['item.name', 'item.code', 'item.pinYin']
			}
		},
		disabled: Boolean,
		// 是否开启防错校验按钮，默认不开启
		showMistakeCheck: {
			type: Boolean,
			default: false
		},
		showBatchSet: {
			type: Boolean,
			default: false
		}
	},
	data () {
		return {
			btnPopperVisible: false,
			settingPopperVisible: false,
			parentDialog: null,
			tableSearchKey: '',
			saveToastDebounce: this.$fxUtils.debounce(),
			rowVerification: this.$fxUtils.fxDataVerification(),
			loading: false
		}
	},
	computed: {
		tableDataComputed () {
			return this.tableData.filter(item => {
				return this.$fxUtils.fuzzyQueryObj(item, this.tableSearchKey, this.searchProps)
			})
		},
		isEditing () {
			return this.tableData.some(item => {
				return !!item.isEdit
			})
		},
		isEditingRow () {
			return this.tableData.find(item => {
				return !!item.isEdit
			})
		},
		isEditingRowIndex () {
			return this.tableData.findIndex(item => {
				return !!item.isEdit
			})
		},
		validateColumn () {
			return this.tableColumn.filter(item => {
				return typeof item.validate === 'function'
			})
		},
		expandRowSlot () {
			return !!this.$slots['row-expand'] || typeof this.$scopedSlots['row-expand'] === 'function'
		}
	},
	created () {
		this.parentDialog = this.$fxUtils.vFindParentByName(this, 'wind-dialog')
	},
	methods: {
		clearSearchKey () {
			this.tableSearchKey = ''
		},
		// [public]开启编辑状态
		setRowEdit (row, type) {
			if (this.disabled) {
				return false
			}
			const index = row.$fxIndex
			if (this.isEditingRowIndex === index && this.isEditing) {
				return Promise.resolve()
			} else {
				return this.doEditingSave().then(() => {
					return this.doSetRowEdit(row, index, type)
				})
			}
		},
		// 编辑未保存的row
		doEditingSave () {
			return this.isEditing ? this.onSaveDetails() : Promise.resolve()
		},
		// 开启行编辑之前的行为
		doSetRowEdit (row, index, type) {
			return this.fpBeforeRowEdit(row, index, type).then(() => {
				return this.setRowEditHandler(row, index, type).then(() => {
					// row.$fxCalculation = this.$fxUtils.createUUID()
					// this.$fxCalculation.setCache(row)
					this.rowVerification.resetData(row)
					return Promise.resolve(row, index, type)
				})
			})
		},
		// 开启行编辑的方法
		setRowEditHandler (row, index, type) {
			return new Promise(resolve => {
				if (index >= this.tableData.length || index < 0) {
					return false
				}
				this.$set(this.tableData[index], 'isEdit', true)
				this.$nextTick(() => {
					if (typeof this.fpOnRowEdit === 'function') {
						this.fpOnRowEdit(row, index, type).then(resolve)
					} else {
						if (this.tableEditColumnProp.length > 0) {
							this.setListCellFocus(type || this.tableEditColumnProp[0])
						}
						resolve()
					}
				})
			})
		},
		// 关闭行编辑的方法
		setRowUnEdit () {
			return new Promise(resolve => {
				this.tableData.forEach((item, itemIndex) => {
					this.$set(this.tableData[itemIndex], 'isEdit', false)
				})
				resolve()
			})
		},
		// [public]新增一行方法
		onAddOnce () {
			this.btnPopperVisible = false
			this.tableSearchKey = ''
			this.fpSaveMain().then(this.doEditingSave).then(() => {
				this.fpInitAddDetailsData().then(res => {
					const row = {
						id: '',
						// sortNum: 0,
						// $fxCalculation: this.$fxUtils.createUUID(),
						...res
					}
					// this.$fxCalculation.setCache(row)
					this.tableData.push(row)
					const index = this.tableData.length - 1
					this.setRowEditHandler(row, index)
					this.$refs.listTable.scrollToBottom()
				})
			})
		},
		// 保存明细方法 todo
		onSaveDetails () {
			return new Promise(resolve => {
				const row = this.isEditingRow
				const hasEdit = !this.rowVerification.checkData(row)
				this.$refs.listTable.verificationRowData(row).then(this.setRowUnEdit).then(() => {
					if (typeof this.fpSaveDetails === 'function' && hasEdit) {
						this.loading = true
						return this.fpSaveDetails(row).then(res => {
							this.loading = false
							this.toastSaveDetials()
							if (res && !row.id) {
								row.id = res.id
							}
							resolve()
						})
					} else {
						resolve()
					}
				})
			})
		},
		toastSaveDetials () {
			this.saveToastDebounce(500).then(() => {
				this.$notify({
					title: '成功',
					message: '明细保存成功',
					type: 'success',
					position: 'bottom-right',
					duration: 2000
				})
			})
		},
		// 点击保存明细按钮
		onSaveDetailsClick () {
			return this.doEditingSave()
		},
		// [public]行编辑最后一列触发回车事件的方法
		doRowEditEnter () {
			if (this.isEditingRowIndex === this.tableData.length - 1) {
				this.canAdd ? this.onAddOnce() : this.doEditingSave()
			} else {
				this.setRowEdit(this.getRowByIndex(this.isEditingRowIndex + 1))
			}
		},
		// 根据index获取row
		getRowByIndex (index) {
			return this.tableData.find(item => {
				return item.$fxIndex === index
			})
		},
		// 点击删除按钮
		onDeleteClick () {
			return this.$refs.listTable.getSelectedRows().then(res => {
				return this.$fxConfirm('是否确定删除所选明细？').then(() => {
					this.$refs.listTable.clearSelected()
					const addRow = res.find(item => {
						return item.id === ''
					})
					if (addRow && res.length === 1) {
						this.tableData.splice(addRow.$fxIndex, 1)
						return Promise.resolve()
					} else {
						const ids = res.filter(item => {
							return !!item.id
						}).map(item => {
							return item.id
						})
						this.$refs.listTable.clearSelected()
						return this.fpDeleteDetails(ids).then((res) => {
							this.$emit('on-details-refresh')
							return Promise.resolve()
						})
					}
				})
			}).catch(() => {
			})
		},
		onMistakeCheck () {
			this.fpSaveMain().then(this.doEditingSave).then(() => {
				this.$emit('on-mistake-check-click')
			})
		},
		setListCellFocus (cellEvent) {
			if (typeof cellEvent === 'string') {
				const _cellEvent = {
					columnProp: cellEvent,
					row: this.isEditingRow,
					index: this.isEditingRowIndex
				}
				this.$refs.listTable.setListCellFocus(_cellEvent)
			} else {
				this.$refs.listTable.setListCellFocus(cellEvent)
			}
		},
		onMulitySettingClick () {
			this.getSelectRows().then(this.doEditingSave).then(() => {
			}).catch(() => {
				setTimeout(() => {
					this.settingPopperVisible = false
				}, 0)
			})
		},
		// [public]获取当前选中的明细
		getSelectRows () {
			return this.$refs.listTable.getSelectedRows()
		},
		// [public]检查当前是否处于非保存状态 或 是否不存在明细
		checkDetailsUnSaving () {
			// return new Promise(resolve => {
			// 	if (this.tableData.length === 0) {
			// 		const error = '请添加明细'
			// 		this.$fxMessage.warning(error)
			// 	} else {
			// 		this.doEditingSave().then(resolve)
			// 	}
			// })
			return this.doEditingSave()
		},
		closeMulitySettingPopver () {
			this.settingPopperVisible = false
		},
		onFullScreen () {
			if (this.$fxUtils.isDef(this.showFullScreenBtn)) {
				this.$emit('on-full-screen-click', this.showFullScreenBtn)
			} else {
				this.parentDialog ? this.parentDialog.onFullScreen() : this.$fxMessage.warning('全屏设置失败')
				this.$emit('on-full-screen')
			}
		},
		offFullScreen () {
			if (this.$fxUtils.isDef(this.showFullScreenBtn)) {
				this.$emit('on-full-screen-click', this.showFullScreenBtn)
			} else {
				this.parentDialog ? this.parentDialog.offFullScreen() : this.$fxMessage.warning('取消全屏设置失败')
				this.$emit('off-full-screen')
			}
		},
		onSearchKeyChange (val) {
			this.doEditingSave().then(() => {
				this.tableSearchKey = val
			})
		},
		onAllExpandClick () {
			this.doEditingSave().then(() => {
				this.$refs.listTable.setAllExpand()
			})
		},
		onAllFoldclick () {
			this.doEditingSave().then(() => {
				this.$refs.listTable.setAllFlod()
			})
		}
	}
}
</script>
<style lang="stylus" scoped>
@import '~$assets/stylus/varsty.styl'
.fx-details-table {
	.tools-left, .tools-right {
		display:flex
		flex-direction: row
		align-items: center
	}
	.tools-left {
		flex: 1
		display:flex
		flex-direction: row
		&-left {
			flex: 1
		}
	}
	.details-table-empty {
		.details-list-empty-icon {
			height: 50px
			width: 50px
		}
		.details-list-empty-text {
			height: 30px
			line-height: 30px
		}
	}
	.table-search-input {
		width: 200px
	}
}
.details-info__btn-popper {
	.btn-popper-container {
		display: flex
		flex-direction: column
		.popper-btn {
			margin-top: 10px
			margin-left: 0px
		}
	}
}
</style>
